﻿using Contracts;
using LPLS.PluginCommon.ModulePlugin;
using Newtonsoft.Json;
using Prism.Ioc;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace LPLS.PluginCommon
{
    public abstract class ModuleBaseModule : IModule
    {

        public static IContainerRegistry _containerRegistry;
        public readonly IRegionManager _regionManager;
        public readonly INavigationRegistry _navigationRegistry;
        public readonly IModuleEventAggregator _moduleEventAggregator;

        private List<NavigationItem> _dynamicNavigationItems = new List<NavigationItem>();
        private ConfigModel _config;

        public ModuleBaseModule(
            IRegionManager regionManager,
            INavigationRegistry navigationRegistry,
            IModuleEventAggregator moduleEventAggregator )
        {
            _regionManager = regionManager;
            _navigationRegistry = navigationRegistry;
            _moduleEventAggregator = moduleEventAggregator;
           // _containerRegistry= containerRegistry;
            // 读取配置文件（假设配置文件位于主程序目录）
            var configPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json");
            var json = File.ReadAllText(configPath);
            _config = JsonConvert.DeserializeObject<ConfigModel>(json);
        }

        public void OnInitialized(IContainerProvider containerProvider)
        {
            // 注册动态生成的导航项
            foreach (var item in _dynamicNavigationItems)
            {
                _navigationRegistry.RegisterNavigationItem(item);
            }
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
          
            var assembly = Initialize();


            // 处理所有 ViewModel 类型
            var viewModelTypes = assembly.GetTypes()
                .Where(t => t.Name.EndsWith("ViewModel") && !t.IsAbstract)
                .ToList();
            foreach (var type in viewModelTypes)
            {
                // 检查是否包含 ViewModelMetadata 特性
                var attribute = type.GetCustomAttribute<ViewModelMetadataAttribute>();
                if (attribute != null)
                {
                    // 根据配置筛选符合条件的 ViewModel
                    if ((attribute.ProjectID == _config.ProjectID && attribute.Version == _config.Version) ||
                        attribute.IsCommon)
                    {
                        // 注册 ViewModel（根据生命周期）
                        var lifetime = attribute.Lifecycle;
                        if (lifetime == Lifecycle.Singleton)
                        {
                            containerRegistry.RegisterSingleton(type);
                        }
                        else if (lifetime == Lifecycle.Transient)
                        {
                            containerRegistry.Register(type);
                        }
                        //  查找对应的 View（假设命名规则为[ViewModelNameWithoutModel] + "View"）
                        var viewTypeName = type.FullName.Replace("ViewModel", "View");

                        var name = viewTypeName.Split('.')[viewTypeName.Split('.').Length - 1];
                        var viewType = assembly.GetType(viewTypeName);
                        if (viewType != null)
                        {
                            // 注册导航 View
                            containerRegistry.RegisterForNavigation(viewType, name);

                            // 收集导航项信息
                            _dynamicNavigationItems.Add(new NavigationItem
                            {
                                Name = attribute.ViewModelName,
                                Icon = "📊", // 可根据特性扩展 Icon 字段
                                NavigationPath = name
                            });
                        }
                    }
                }
                else
                {

                    // 非特性 ViewModel - 使用瞬态生命周期
                    containerRegistry.Register(type);
                    //var viewTypeName = type.FullName.Replace("ViewModel", "View");
                    //var name = viewTypeName.Split('.')[viewTypeName.Split('.').Length - 1];
                    //var viewType = assembly.GetType(viewTypeName);

                    //if (viewType != null)
                    //{
                    //    // 注册ViewModel
                    //    containerRegistry.RegisterSingleton(type);

                    //    // 注册View时关联ViewModel
                    //    containerRegistry.RegisterForNavigation(viewType, type.Name);
                    //}

                }
            }


            // 处理所有 View 类型
            var viewTypes = assembly.GetTypes()
                .Where(t => t.Name.EndsWith("View") && !t.IsAbstract)
                .ToList();

            foreach (var viewType in viewTypes)
            {
                // 确保视图已注册（如果尚未注册）
                if (!containerRegistry.IsRegistered(viewType))
                {
                    containerRegistry.Register(viewType);
                }
            }

        }


        public virtual void LoadRegisterTypes(IContainerRegistry containerRegistry) { 
        
        
        }

        public abstract Assembly Initialize();
    }

    public class ConfigModel
    {
        public string ProjectID { get; set; }
        public string Version { get; set; }
    }




    /// <summary>
    /// 基础的ViewModel
    /// </summary>
    public class ViewModelBase : BindableBase
    {


        public ViewModelBase(IContainerProvider containerProvider) {

            _containerProvider = containerProvider;
        }
        public  readonly IContainerProvider _containerProvider;

        public  TabItem CreateTabItem(string header, Type viewType)
        {
            // 创建视图
            var view = _containerProvider.Resolve(viewType) as FrameworkElement;

            // 创建代理容器
            var contentHost = new ContentControl();

            // 保持原始 DataContext
            contentHost.Content = view;
            contentHost.DataContext = view.DataContext;

            return new TabItem
            {
                Header = header,
                Content = contentHost // 使用代理容器
            };
        }




    }
}